I want to be able to display a 'clicker' variable, storing the number of clicks on a certain element, and then display it when i click on another element.
per = a * 6.6666 so I tried again and it wont work the result stay 0 but if I change the value of a to 1 it shows 6.6666 so the calculation is working fine but it is not taking the value of a based on how many times I click it just take the value I gave in the script ...
var a = 0 ;
const six = 6.6666;
var per = a * six;
$(".mychoice").click(function () {
(a++);
});
$(".show").click(function () {
$("#ss").text( per );
});
Calculations are done when you tell them to be done.
If you change the value of a in a click event, then that value doesn't travel back through time so that a is the new value back when you read it and used it to multiply six.
If you want to redo that calculation when something is clicked then you need to write that expression in that click event handler function.
Keep in mind that a and per are two distinct locations in memory, therefore, you have to update the per variable along with the a variable.
var a = 0;
const six = 6.6666;
var per = a * six;
$(".mychoice").click(function () {
(a++);
// memory location labelled "a" has changed
// update memory location labelled "per" accordingly
per = a * six;
});
$(".show").click(function () {
$("#ss").text(per);
});
var per = a * six;
The calculation is executed and stored in the per variable as soon as the line is executed, not when you reference the per variable.
If you want to calculate the value at a later time, use an (arrow) function instead.
// define `per` as arrow function with 0 arguments
var per = () => a * six;
Then you evoke the function when you need the result:
$(".show").click(function () {
$("#ss").text( per() );
});
In this scenario doing the calculation directly, without defining a function, might be cleaner.
$(".show").click(function () {
$("#ss").text(a * six);
});